<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="78px">
      <el-form-item label="规格名称" prop="ruleName">
        <el-input v-model="queryParams.ruleName" placeholder="请输入规格名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="规格值" prop="ruleValue">
        <el-input v-model="queryParams.ruleValue" placeholder="请输入规格值" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['store:product-rule:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['store:product-rule:export']">导出</el-button>
      </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

            <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="规格名称" align="center" prop="ruleName" />
      <el-table-column label="规格值" align="center">
        <template v-slot="scope">
          <div>
            <span v-for="spec in scope.row.specs" :key="spec.name" style="margin-right: 8px;">
              {{ spec.name }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="商品属性" align="left">
        <template v-slot="scope">
          <div style="text-align: left;">
            <div v-for="spec in scope.row.specs" :key="spec.name" style="margin-bottom: 4px;">
              <span style="font-weight: bold;">{{ spec.name }}</span>
              <span style="margin-left: 8px;">{{ spec.values.join(',') }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row)">
            修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['store:product-rule:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <ProductRuleForm ref="formRef" @success="getList" />
    </div>
</template>

<script>
import * as ProductRuleApi from '@/api/store/rule';
import ProductRuleForm from './ProductRuleForm.vue';
export default {
  name: "ProductRule",
  components: {
          ProductRuleForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
              // 总条数
        total: 0,
      // 商品规则值(规格)列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
                    pageNo: 1,
            pageSize: 10,
        ruleName: null,
        ruleValue: null,
      },
      formData: {
        id: undefined,
        ruleName: undefined,
        ruleValue: undefined,
        deleted: 0
      },
            };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await ProductRuleApi.getProductRulePage(this.queryParams);
        let rawList = res.data.list || [];

        // 1. 前端过滤
        if (this.queryParams.ruleName) {
          rawList = rawList.filter(item => item.ruleName && item.ruleName.includes(this.queryParams.ruleName));
        }
        if (this.queryParams.ruleValue) {
          rawList = rawList.filter(item => item.ruleValue && item.ruleValue.includes(this.queryParams.ruleValue));
        }

        // 2. 合并
        const map = {};
        rawList.forEach(item => {
          if (!map[item.id]) {
            map[item.id] = {
              id: item.id,
              ruleName: item.ruleName,
              ruleValue: item.ruleValue,
              rawItems: []
            };
          }
          map[item.id].rawItems.push(item);
        });
        this.list = Object.values(map).map(item => {
          let specs = [];
          try {
            specs = JSON.parse(item.ruleValue)
              .map(i => ({
                name: i.value,
                values: i.detail
              }));
          } catch (e) {}
          return {
            id: item.id,
            ruleName: item.ruleName,
            specs,
            rawItems: item.rawItems // 保留原始数据
          };
        });
        // 3. 排序
        this.list.sort((a, b) => b.id - a.id);

        // 4. 分页（如果后端返回的是全部数据）
        // const start = (this.queryParams.pageNo - 1) * this.queryParams.pageSize;
        // const end = start + this.queryParams.pageSize;
        // this.list = this.list.slice(start, end);

        this.total = this.list.length; // 用合并后的总数
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(row) {
      this.$refs["formRef"].open(row);
      console.log('row.specs:', row.specs);
      console.log('this.specList:', this.specList);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除商品规则值(规格)编号为"' + id + '"的数据项?')
      try {
       await ProductRuleApi.deleteProductRule(id);
       await this.getList();
       this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有商品规则值(规格)数据项?');
      try {
        this.exportLoading = true;
        // 只导出指定的列，并设置对应的中文名称
        const exportParams = {
          ...this.queryParams,
          exportColumns: [
            { field: 'ruleName', title: '规格名称' },
            { field: 'attrName', title: '商品规格' },
            { field: 'detailItems', title: '商品属性' }
          ]
        };
        const data = await ProductRuleApi.exportProductRuleExcel(exportParams);
        this.$download.excel(data, '商品规则值(规格).xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
              }
};
</script>
